import 'package:flutter/material.dart';
import 'package:get/get.dart' hide WidgetPaddingX;
import 'package:hotpot/basic/app_colors.dart';
import 'package:hotpot/extensions/data.dart';
import 'package:hotpot/models/res_country.dart';
import 'package:hotpot/models/res_country_state.dart';
import 'package:hotpot/odoo/odoo_api.dart';
import 'package:hotpot/pages/order/widgets/scan_widget.dart';
import 'package:hotpot/route/route_ext.dart';
import 'package:hotpot/widgets/popup_btn.dart';
import 'package:hotpot/widgets/styles/icon_box.dart';
import 'package:hotpot/widgets/styles/text_field_box.dart';
import 'package:hotpot/widgets/widget_ext.dart';
import 'package:hotpot/widgets/z_container.dart';
import 'package:pretty_qr_code/pretty_qr_code.dart';

class AddUserPage extends StatefulWidget {
  const AddUserPage({super.key});

  @override
  State<AddUserPage> createState() => _AddUserPageState();
}

class _AddUserPageState extends State<AddUserPage> {
  final nameCtl = TextEditingController();
  final emailCtl = TextEditingController();

  // final companyCtl = TextEditingController();
  final vatCtl = TextEditingController();
  final phoneCtl = TextEditingController();
  final mobileCtl = TextEditingController();

  // final streetCtl = TextEditingController();
  final zipCtl = TextEditingController();
  final cityCtl = TextEditingController();
  ResCountry? country;
  ResCountryState? countryState;

  List<ResCountry> countryList = [];
  List<ResCountryState> countryStateList = [];

  var editSuccess = false.obs;

  var showScan = false.obs;

  var barcode = ''.obs;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    OdooApi.getResCountry().then((value) {
      countryList = value;
      var index = countryList.indexWhere((element) => element.name == 'Spain');
      if (index != -1) {
        _selectCountry(countryList[index]);
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.baColor,
      body: Obx(() {
        if (editSuccess.value) {
          return Column(
            children: [
              147.hSizedBox,
              'images/img_success.png'.assetImage(width: 48),
              10.hSizedBox,
              '¡Gracias!'.text(size: 8, bold: true, color: Colors.white),
              const SizedBox().expanded(),
              ZContainer(
                color: const Color(0xFF22CE67),
                height: 31,
                width: 147,
                radius: 3,
                alignment: Alignment.center,
                child: 'Cerra'.text(size: 10, bold: true, color: Colors.white),
              ).gestureDetector(onTap: pop),
              67.hSizedBox,
            ],
          ).sizedBox(width: double.infinity);
        }
        return Stack(
          children: [
            Row(
              children: [
                ZContainer(
                  width: 174,
                  height: double.infinity,
                  color: const Color(0xFF1F1D2B),
                  child: Column(
                    children: [
                      60.hSizedBox,
                      const ZContainer(
                        color: Color(0xFF252836),
                        radius: 8,
                        width: 68,
                        height: 68,
                        child: IconBox(Icons.person, 40, 38, bgColor: Colors.transparent),
                      ),
                      110.hSizedBox,
                      Obx(
                        () {
                          if (barcode.value.isEmpty) {
                            return Column(
                              children: [
                                'Scan Tarjeta'.text(size: 7, bold: true, color: Colors.white),
                                // 8.hSizedBox,
                                const IconBox(Icons.qr_code, 48, 46, bgColor: Colors.transparent).gestureDetector(onTap: () {
                                  showScan.value = true;
                                }),
                              ],
                            );
                          } else {
                            return Stack(
                              children: [
                                ZContainer(
                                  margin: const EdgeInsets.only(top: 3),
                                  width: 144,
                                  height: 144,
                                  radius: 12,
                                  color: const Color(0xFFF8F8F8),
                                  alignment: Alignment.center,
                                  child: Column(
                                    children: [
                                      22.hSizedBox,
                                      PrettyQrView(
                                        qrImage: QrImage(
                                          QrCode(8, QrErrorCorrectLevel.H)..addData(barcode.value),
                                        ),
                                        decoration: const PrettyQrDecoration(),
                                      ).sizedBox(width: 78),
                                      7.hSizedBox,
                                      barcode.value.text(size: 12, color: Colors.black),
                                    ],
                                  ),
                                ),
                                const IconBox(Icons.close, 11, 9, bgColor: Colors.red)
                                    .gestureDetector(onTap: () => barcode.value = '')
                                    .positioned(right: 0),
                              ],
                            );
                          }
                        },
                      ),
                    ],
                  ),
                ),
                SingleChildScrollView(
                  child: Column(
                    children: [
                      const IconBox(Icons.highlight_remove_rounded, 18, 16, bgColor: Colors.transparent)
                          .paddingOnly(top: 9, right: 9)
                          .gestureDetector(onTap: pop)
                          .alignRight(),
                      'Registo'.text(size: 15, bold: true, color: Colors.white).alignLeft(),
                      22.hSizedBox,
                      TextFieldBox(title: 'Name', must: true, controller: nameCtl),
                      5.hSizedBox,
                      TextFieldBox(title: 'Email', controller: emailCtl),
                      5.hSizedBox,
                      TextFieldBox(title: 'NIF/CIF', controller: vatCtl),
                      5.hSizedBox,
                      Row(
                        children: [
                          TextFieldBox(title: 'Telefono', controller: phoneCtl).expanded(),
                          9.wSizedBox,
                          TextFieldBox(title: 'Movil', must: true, controller: mobileCtl).expanded(),
                        ],
                      ),
                      5.hSizedBox,
                      Row(
                        children: [
                          TextFieldBox(title: 'Ciudad', controller: cityCtl).expanded(),
                          9.wSizedBox,
                          PopupBtn<ResCountryState>(
                            title: 'Provincia',
                            list: countryStateList,
                            getText: (data) => data.displayName ?? '',
                            text: countryState?.displayName,
                            onChanged: _selectCountryState,
                          ).expanded(),
                        ],
                      ),
                      5.hSizedBox,
                      Row(
                        children: [
                          TextFieldBox(title: 'Código postal', controller: zipCtl).expanded(),
                          9.wSizedBox,
                          const SizedBox().expanded(),
                        ],
                      ),
                      38.hSizedBox,
                      ZContainer(
                        color: const Color(0xFF22CE67),
                        height: 31,
                        width: 212,
                        radius: 3,
                        alignment: Alignment.center,
                        margin: const EdgeInsets.symmetric(horizontal: 17),
                        child: 'OK'.text(size: 10, bold: true, color: Colors.white),
                      ).gestureDetector(onTap: _register),
                      23.hSizedBox,
                    ],
                  ).paddingSymmetric(horizontal: 20),
                ).expanded(),
              ],
            ),
            Obx(
              () => ScanWidget(
                () => showScan.value = false,
                null,
                onResult: (code) {
                  barcode.value = code;
                  showScan.value = false;
                },
                right: false,
              ).visibility(showScan.value),
            ),
          ],
        );
      }),
    );
  }

  void _register() async {
    if (nameCtl.text.isEmpty) {
      showToast('请输入用户名');
      return;
    } else if (mobileCtl.text.isEmpty) {
      showToast('请输入手机号');
      return;
    }
    var barcode = this.barcode.value; // UserUtils.createUnique();
    var canRegister = false, emptyEmail = emailCtl.text.isEmpty, emptyMobile = false;
    if (emailCtl.text.isNotEmpty) {
      emptyEmail = await OdooApi.checkEmail(emailCtl.text);
    }
    emptyMobile = await OdooApi.checkMobile(mobileCtl.text);
    canRegister = emptyEmail && emptyMobile;
    if (canRegister) {
      var userId = await OdooApi.register(nameCtl.text, emailCtl.text, mobileCtl.text, barcode);
      var user = await OdooApi.getUser(userId: userId);
      var data = await OdooApi.editPartner(
        int.parse(user!.partnerId.firstValue!),
        phone: phoneCtl.text,
        city: cityCtl.text,
        // companyName: companyCtl.text,
        vat: vatCtl.text,
        zip: zipCtl.text,
        // street: streetCtl.text,
        mobile: mobileCtl.text,
        countryId: country?.id,
        stateId: countryState?.id,
        barcode: barcode,
      );
      if (data) {
        OdooApi.getResPartner(id: int.parse(user.partnerId.firstValue!)).then((value) {
          // UserUtils.init(value!);
          // Routes.home.popAndPushNamed(context);
          // print(value);
          editSuccess.value = true;
        });
      } else {
        showToast('创建失败');
      }
    } else {
      showToast('账号已存在');
    }
  }

  void _selectCountry(ResCountry value) {
    country = value;
    countryState = null;
    OdooApi.getResCountryState(value.id!).then((value) {
      countryStateList = value;
      setState(() {});
    });
  }

  void _selectCountryState(ResCountryState value) {
    countryState = value;
    setState(() {});
  }
}
